using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using MoonFramework.Attribute;
using MoonFramework.Template;
using UnityEngine;
using Object = UnityEngine.Object;

namespace MoonFramework.Scripts.Resoure
{
	/// <summary>
	/// 资源加载模块
	/// </summary>
	[Pool]
	public class ResourceManager : BaseManager<ResourceManager>
	{ 
		private readonly Dictionary<string, Object> _assetResources = new();

		//同步加载资源
		public T Load<T>(string name, Action<T> _fun = null) where T : UnityEngine.Object
		{
			T res;
			if (_assetResources.TryGetValue(name, out var assetRes))
				res = assetRes as T;
			else
			{
				res = Resources.Load<T>(name);
				_assetResources.TryAdd(name, res);
			}

			var obj = res;

			//如果是GameObject类型
			if (res is GameObject)
				obj = Object.Instantiate(res);
			
			_fun?.Invoke(obj);
			return obj;
		}


		public async UniTask<T> LoadAsync<T>(string name, Action<T> _fun = null) where T : UnityEngine.Object
		{
			UnityEngine.Object res = null;

			if (_assetResources.TryGetValue(name, out var assetRes))
			{
				res = assetRes as T;
			}

			// 异步加载资源
			if (!res)
			{
				res = await TureLoadAsync<T>(name);

				if (!_assetResources.ContainsKey(name))
					_assetResources.TryAdd(name, res);
			}

			var obj = res;
			if (res is GameObject)
				obj = Object.Instantiate(res);
			_fun?.Invoke(obj as T);
			return obj as T;
		}

		private async UniTask<T> TureLoadAsync<T>(string name) where T : UnityEngine.Object
		{
			var resRequest = Resources.LoadAsync<T>(name);

			await resRequest;

			var obj = resRequest.asset;

			return obj as T;
		}
	}
}